package com.tuanzi.loan.business.repository.system.impl;

import static com.tuanzi.loan.generated.jooq.loan.tables.LoanDictionary.LOAN_DICTIONARY;

import java.util.List;

import org.jooq.Record;
import org.jooq.RecordMapper;
import org.jooq.impl.TableImpl;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import com.tuanzi.loan.business.entity.system.Dictionary;
import com.tuanzi.loan.business.repository.system.custom.DictionaryRepositoryCustom;
import com.tuanzi.loan.core.repository.JOOQBaseRepository;
import com.tuanzi.loan.vo.request.system.DictionarySearchRequest;
import com.tuanzi.loan.vo.response.system.DictionarySearchResponse;

/**
 * @author Ray 2017/09/21
 */
@SuppressWarnings({ "rawtypes" })
public class DictionaryRepositoryImpl extends JOOQBaseRepository implements DictionaryRepositoryCustom {

	@Override
	protected TableImpl getTable() {
		return LOAN_DICTIONARY;
	}

	@Override
	public Page<DictionarySearchResponse> list(DictionarySearchRequest searchRequest, Pageable pageable) {
		
		contains(LOAN_DICTIONARY.CODE, searchRequest.getCode());
		contains(LOAN_DICTIONARY.NAME, searchRequest.getName());
		contains(LOAN_DICTIONARY.VALUE1, searchRequest.getValue1());
		contains(LOAN_DICTIONARY.VALUE2, searchRequest.getValue2());
		contains(LOAN_DICTIONARY.VALUE3, searchRequest.getValue3());
		contains(LOAN_DICTIONARY.VALUE4, searchRequest.getValue4());
		contains(LOAN_DICTIONARY.DESCRIPTION, searchRequest.getDescription());
		eq(LOAN_DICTIONARY.ENABLE,searchRequest.getEnable());
		orderBy(LOAN_DICTIONARY.CODE, Sort.Direction.ASC);
		orderBy(LOAN_DICTIONARY.SORT, Sort.Direction.ASC);
		return search(pageable, new DictionarySearchResponseRecordMapper());
	}

	@Override
	public List<Dictionary> findAllByCodes(List<String> codes) {
		in(LOAN_DICTIONARY.CODE, codes);
		eq(LOAN_DICTIONARY.ENABLE, true);
		return search(Dictionary.class);
	}

	private final class DictionarySearchResponseRecordMapper implements RecordMapper<Record, DictionarySearchResponse> {

		@Override
		public DictionarySearchResponse map(Record record) {
			DictionarySearchResponse response = new DictionarySearchResponse();
			response.setId(record.get(LOAN_DICTIONARY.ID));
			response.setCode(record.get(LOAN_DICTIONARY.CODE));
			response.setName(record.get(LOAN_DICTIONARY.NAME));
			response.setValue1(record.get(LOAN_DICTIONARY.VALUE1));
			response.setValue2(record.get(LOAN_DICTIONARY.VALUE2));
			response.setValue3(record.get(LOAN_DICTIONARY.VALUE3));
			response.setValue4(record.get(LOAN_DICTIONARY.VALUE4));
			response.setSort(record.get(LOAN_DICTIONARY.SORT));
			response.setDescription(record.get(LOAN_DICTIONARY.DESCRIPTION));
			response.setEnable(record.get(LOAN_DICTIONARY.ENABLE));
			return response;
		}
	}
}
